package com.lib.notepadapp.ui;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.lib.notepadapp.R;
import com.lib.notepadapp.bean.NotePad;
import com.lib.notepadapp.databinding.ActivityEditBinding;
import com.lib.notepadapp.db.MyDbHelper;
import com.lib.notepadapp.utils.TimeUtil;

import java.io.Serializable;

public class EditActivity extends AppCompatActivity {

    private ActivityEditBinding binding;

    private MyDbHelper myDbHelper;
    private NotePad notePad;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        binding=ActivityEditBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        Serializable serializable = getIntent().getSerializableExtra("notepad");
        if (serializable==null){
            binding.titleTv.setText("添加记录");
        }else {
            binding.titleTv.setText("修改记录");
            notePad=(NotePad) serializable;
            binding.contentEt.setText(notePad.getContent());
        }

        binding.backIv.setOnClickListener(v -> finish());

        myDbHelper=new MyDbHelper(this);
        binding.clearIv.setOnClickListener(v->binding.contentEt.setText(""));

        binding.saveIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = binding.contentEt.getText().toString().trim();
                if (TextUtils.isEmpty(content)){
                    Toast.makeText(EditActivity.this,"请输入内容",Toast.LENGTH_SHORT).show();
                    return;
                }
                //判断是新增还是修改
                if (notePad==null){
                    notePad = new NotePad();
                    notePad.setContent(content);
                    notePad.setTime(TimeUtil.getTime());
                    myDbHelper.insert(notePad);
                    Toast.makeText(EditActivity.this,"新增成功",Toast.LENGTH_SHORT).show();
                }else {
                    notePad.setContent(content);
                    notePad.setTime(TimeUtil.getTime());
                    myDbHelper.update(notePad);
                    Toast.makeText(EditActivity.this,"更新成功",Toast.LENGTH_SHORT).show();

                }
                setResult(RESULT_OK);
                finish();
            }
        });
    }
}